package com.batchengine.db.handlers;

import com.batchengine.db.RowProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <code>ResultSetHandler</code> implementation that converts a
 * <code>ResultSet</code> into a <code>List</code> of beans. This class is
 * thread safe.
 *
 * @see com.batchengine.db.ResultSetHandler
 */
public class BeanListHandler extends GenericListHandler {

    /**
     * The Class of beans produced by this handler.
     */
    private Class type = null;

    /**
     * The RowProcessor implementation to use when converting rows
     * into beans.
     */
    private RowProcessor convert = ArrayHandler.ROW_PROCESSOR;

    /**
     * Creates a new instance of BeanListHandler.
     *
     * @param type The Class that objects returned from <code>handle()</code>
     *             are created from.
     */
    public BeanListHandler(Class type) {
        this.type = type;
    }

    /**
     * Creates a new instance of BeanListHandler.
     *
     * @param type    The Class that objects returned from <code>handle()</code>
     *                are created from.
     * @param convert The <code>RowProcessor</code> implementation
     *                to use when converting rows into beans.
     */
    public BeanListHandler(Class type, RowProcessor convert) {
        this.type = type;
        this.convert = convert;
    }

    /**
     * Convert the <code>ResultSet</code> row into a bean with
     * the <code>Class</code> given in the constructor.
     *
     * @return A bean, never <code>null</code>.
     * @throws SQLException if a database access error occurs
     */
    protected Object handleRow(ResultSet rs) throws SQLException {
        return this.convert.toBean(rs, type);
    }

}
